package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.utils.RRException;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private WareSkuService wareSkuService;

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 这个就是回显的就是我们新建和以领取的
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils unreceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new LambdaQueryWrapper<PurchaseEntity>().eq(PurchaseEntity::getStatus, 0).or().eq(PurchaseEntity::getStatus, 1)
        );

        return new PageUtils(page);
    }

    /**
     * 先判断purchaseId
     * 采购单合并
     *
     * @param mergeVo
     * @return
     */
    @Transactional // 事务因为你可以能你的PurchaseEntity是没有创建的
    @Override
    public String purchaseMerge(MergeVo mergeVo) {

        List<Long> items = mergeVo.getItems();
        // TODO 首先我们要判断一下我们选择整单的他的状态是新建还是已领取，只有这两种情况才能整单，你想要重复买这个东西就重新加一个采购项出来
        // 只要你选择有不是这两种情况的就重新选择(当然你也可以说符合两种情况的就加入进去，对都不是进行特殊的判断)
        // 批量查询出来
        List<PurchaseDetailEntity> purchaseDetailEntities = (List<PurchaseDetailEntity>) purchaseDetailService.listByIds(items);

        for (PurchaseDetailEntity purchaseDetailEntity : purchaseDetailEntities) {
            if (purchaseDetailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()
                    || purchaseDetailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.FINISH.getCode()
                    || purchaseDetailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.BUYING.getCode()) {
//                throw new RRException("");
                return "chongfu";
            }
        }


        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            // 新建过来的
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());

            // 新建的时候默认是0 新建状态
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            save(purchaseEntity);

            // 得到采购单id
            purchaseId = purchaseEntity.getId();
        }

        // TODO 确认采购单的状态是0还是1  不判断每一个采购项因为我们同一个东西要分配给多个人才行
//        LambdaQueryWrapper<PurchaseDetailEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(PurchaseDetailEntity::getPurchaseId, purchaseId);
//
//        // 判断采购单id
        PurchaseEntity byId = getById(purchaseId);

//        System.out.println();
//        log.info("状态码是:{}",byId.getStatus());

        if(byId.getStatus() == WareConstant.PurchaseStatusEnum.FINISH.getCode() || byId.getStatus() == WareConstant.PurchaseStatusEnum.RECEIVE.getCode() || byId.getStatus() == WareConstant.PurchaseStatusEnum.HASERROR.getCode()) {
            return "";
        }
//
////        purchaseDetailService.list();
//        if(byId.getStatus() != WareConstant.PurchaseStatusEnum.CREATED.getCode() || byId.getStatus() != WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
//            return;
//        }






        // 还要修改采购单detial的状态
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map((item) -> {
            // 修改采购需求
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            // 设置主键
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        // 批量修改
        purchaseDetailService.updateBatchById(collect);

        // 还要修改我们日期还要进行修改
        // 创建采购单
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        updateById(purchaseEntity);

        return "";
    }

    @Transactional
    @Override
    public void purchaseReceived(List<Long> ids) {
        // 1.并且这个采购单必须是新建或者是已经分配了的
        List<PurchaseEntity> purchaseEntityList = ids.stream().map((id) -> {
            // 得到采购单的实体类
            PurchaseEntity purchaseEntity = getById(id);
            return purchaseEntity;
        }).filter((item) -> {
            // 收集我们的状态必须是新建还有就是必须就是已分配的才行
            return item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).map((item) -> {
            // 改为什么 就是状态修改了2
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            // 设置当时这个领取人员领取的时间
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        // 2.修改我们采购单的状态改为我们的已领取的状态
        updateBatchById(purchaseEntityList);


        // 3.改变采购项的状态
        purchaseEntityList.forEach((item) -> {
            // 根据采购单获取到我们采购项的id
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetialBypurchaseId(item.getId());
//            if (purchaseDetailEntities != null && purchaseDetailEntities.size() > 0) {
            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().map((entity) -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();

                // 设置主键id 我们只修改状态 没有时间就不进行修改
                purchaseDetailEntity.setId(entity.getId());
                // 修改状态
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
//                entity.set
                return purchaseDetailEntity;
            }).collect(Collectors.toList());

//            }

//            if(collect != null && collect.size() > 0) {
            // 下面就进行批量修改
            purchaseDetailService.updateBatchById(collect);
//            }

        });

        //
    }

    /**
     * 完成采购
     *
     * @param purchaseDoneVo
     */
    @Transactional
    @Override
    public void purchaseDone(PurchaseDoneVo purchaseDoneVo) {
        // 1.改变采购单的状态
        // 1.1.获取采购单的id
        Long id = purchaseDoneVo.getId();

        // 1.2.采购单状态
        // 他是要根据采购项来进行的 只有每一个采购项都完成了那么才能说是正确的 不然就是出现了异常

        // 2、每一个采购项的状态
        Boolean flag = true;
        List<PurchaseItemVo> items = purchaseDoneVo.getItems();

        List<PurchaseDetailEntity> updates = new ArrayList<>();

        for (PurchaseItemVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();

            // 这个就是失败  无论是你买少了还是什么原因只要没有买够就都是有异常的
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {

                flag = false;

                purchaseDetailEntity.setStatus(item.getStatus());
                // 设置失败原因
                purchaseDetailEntity.setReason(item.getReason());
                // 设置实际购买数量
                purchaseDetailEntity.setRealNum(item.getRealNum());

                // 增加实际购买库存
                // 3.增加库存(仓库id,skuId,入几个库)
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());

                // 注意这个是实际添加库存的多少
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), item.getRealNum());

            } else {
                // 设置实际购买数量
                purchaseDetailEntity.setRealNum(item.getRealNum());

                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 3.增加库存(仓库id,skuId,入几个库)
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                // 增加库存
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());

            }

            purchaseDetailEntity.setId(item.getItemId());
            updates.add(purchaseDetailEntity);
        }

        // 3.将成功采购的进行入库
        purchaseDetailService.updateBatchById(updates);

        // 1、改变采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());

        updateById(purchaseEntity);


    }

}